﻿using LoadIn.Maps.Bing.Models;
using Orchard;
using Orchard.Caching;
using Orchard.Environment.Extensions;

namespace LoadIn.Maps.Bing.Services
{
    public interface IBingMapsService : IDependency
    {
        string GetApiKey();

        string GetMode();
    }

    [OrchardFeature("LoadIn.Maps.Bing")]
    public class BingMapsService : IBingMapsService
    {
        private readonly IWorkContextAccessor _wca;
        private readonly ICacheManager _cacheManager;
        private readonly ISignals _signals;

        public BingMapsService(IWorkContextAccessor wca, ICacheManager cacheManager, ISignals signals)
        {
            _wca = wca;
            _cacheManager = cacheManager;
            _signals = signals;
        }

        public string GetApiKey()
        {
            return _cacheManager.Get(
                "LoadIn.Maps.Bing.ApiKey",
                ctx =>
                {
                    ctx.Monitor(_signals.When("LoadIn.Maps.Bing.Changed"));
                    WorkContext workContext = _wca.GetContext();
                    var bingmapsSettings =
                        (BingMapsSettingsPart)workContext
                                                  .CurrentSite
                                                  .ContentItem
                                                  .Get(typeof(BingMapsSettingsPart));
                    return bingmapsSettings.ApiKey;
                });
        }

        public string GetMode()
        {
            return _cacheManager.Get(
                "LoadIn.Maps.Bing.Mode",
                ctx =>
                {
                    ctx.Monitor(_signals.When("LoadIn.Maps.Bing.Changed"));
                    WorkContext workContext = _wca.GetContext();
                    var bingmapsSettings =
                        (BingMapsSettingsPart)workContext
                                                  .CurrentSite
                                                  .ContentItem
                                                  .Get(typeof(BingMapsSettingsPart));
                    return bingmapsSettings.Mode;
                });
        }
    }
}